<template>
	<view class="content">
		<template>
			<view class="teps">
				<view class="item_teps" v-for="(item, index) in stepList">
					<template>
						<view class="active_item_imm" v-if="index == currentActive">
							<view class="procefindding">
								<view class="line">
									<view class="left" :class="index == 0 ? 'hidder_line' : ''"></view>
									<view class="active_icons_num">
										{{ index + 1 }}
									</view>

									<view class="right" :class="index == stepList.length - 1 ? 'hidder_line' : ''"></view>
								</view>
								<view class="text">进行中</view>
							</view>
						</view>
						<view class="active_item_imm" v-else>
							<view class="procefindding">
								<view class="line">
									<view class="left" :class="{ rightclolr: currentActive + 1 < index, hidder_line: index == 0 }"></view>
									<view class="" v-if="index < currentActive">
										<uni-icons color="#9ef2a9" type="checkbox" size="30"></uni-icons>
									</view>
									<view v-else class="icons_num">
										{{ index + 1 }}
									</view>
									<view class="right" :class="{ rightclolr: currentActive + 1 <= index, hidder_line: index == 3 }"></view>
								</view>
								<view class="text" v-if="index < currentActive">已完成</view>
								<view class="text clolrb" v-else>未开始</view>
							</view>
						</view>
					</template>
				</view>
			</view>
		</template>

		<view class="content_container" v-if="currentActive == 0">
			<view class="" style="padding:20rpx 0;">
				<view class="">1.保持设备通电,设备处于配网状态</view>
				<view class="" style="margin-top:20rpx">2.链接设备wifi </view>
				<view class="" style="margin-top:20rpx">3.输入家庭wifi的账号密码</view>
				<view class="" style="margin-top:20rpx">4.配网完成后再连接家庭wifi</view>
			</view>
			<button class="content_container_botton" @click="toSetp(1)">下一步</button>
		</view>

		<view class="content_container" v-if="currentActive == 1">
			<view class="" style="padding:20rpx 0;" v-if="currentSystem == 'android'">1.点击wifi列表中的wifi 链接设备Wifi</view>
			<view class="" style="padding:20rpx 0;" v-if="currentSystem == 'ios'">1.确保链接上设备wifi后点击下一步</view>
			<scroll-view class="wifi_list" enhanced 	:show-scrollbar="false"	scroll-y>
				<uni-list>
					<uni-list-item clickable v-for="(item, index) in wifiList" :key="index" @click="onListClick(item,index)">
						<template v-slot:body>
							<view class="" style="flex:1;">
								<view>BSSID:{{item.BSSID}}</view>
								<view>SSID:{{item.SSID}}</view>
							</view>
				
						</template>
						<template v-slot:footer>
							<uni-icons type="locked" size="20"></uni-icons>
						</template>
					</uni-list-item>
				</uni-list>
			</scroll-view>
			<button class="content_container_botton" @click="toSetpCheck(2)">下一步</button>
		</view>
		<view class="content_container" v-if="currentActive == 2">
			<view class="" style="padding:20rpx 0;">
				输入家庭wifi账号密码
			</view>
			<uni-forms-item label="SSID">
				<uni-easyinput v-model="formData.SSID" placeholder="请输入家庭wifi 的 SSID" />
			</uni-forms-item>
			<uni-forms-item label="密码" >
				<uni-easyinput v-model="formData.password" placeholder="请输入家庭wifi 的密码" />
			</uni-forms-item>
			
			<scroll-view  class="wifi_list_two" enhanced 	:show-scrollbar="false"	scroll-y>
				<uni-list>
					<uni-list-item clickable v-for="(item, index) in wifiList" :key="index" @click="onListAdviceClick(item,index)">
						<template v-slot:body>
							<view class="" style="flex:1;">
								<view>BSSID:{{item.BSSID}}</view>
								<view>SSID:{{item.SSID}}</view>
							</view>
				
						</template>
						<template v-slot:footer>
							<uni-icons type="locked" size="20"></uni-icons>
						</template>
					</uni-list-item>
				</uni-list>
			</scroll-view>
			<button class="content_container_botton" @click="toAdviceContent(3)">下一步</button>
		</view>
		
		<view class="content_container" v-if="currentActive == 3">
			<view class="" style="padding:20rpx 0;">
				开始配网
			</view>
			
			
			<!-- <scroll-view  class="wifi_list_two" enhanced 	:show-scrollbar="false"	scroll-y>
				<uni-list>
					<uni-list-item clickable v-for="(item, index) in wifiList" :key="index" @click="onListAdviceClick(item,index)">
						<template v-slot:body>
							<view class="" style="flex:1;">
								<view>BSSID:{{item.BSSID}}</view>
								<view>SSID:{{item.SSID}}</view>
							</view>
				
						</template>
						<template v-slot:footer>
							<uni-icons type="locked" size="20"></uni-icons>
						</template>
					</uni-list-item>
				</uni-list>
			</scroll-view> -->
			<view class="" style="margin-top:auto;display: flex;align-items: center;justify-content: space-around;">
				<button class="content_container_botton" style="width:250rpx;background:#999"  @click="touptemp">返回上一级</button>
				<button class="content_container_botton" style="width:250rpx;" @click="toContent">开始配网</button>
			</view>
			
		</view>
		<!-- 家庭WiFi 密码 -->
	<!-- 	<uni-popup ref="inputDialog" type="dialog">
			<uni-popup-dialog ref="inputClose" mode="input" title="输入wifi密码" placeholder="输入wifi密码" @confirm="dialogInputConfirm"></uni-popup-dialog>
		</uni-popup> -->
		
		<!-- <uni-popup ref="inputDialog" type="dialog">
			<uni-popup-dialog ref="inputClose" mode="input" title="输入wifi密码" placeholder="输入wifi密码" @confirm="dialogInputConfirm"></uni-popup-dialog>
		</uni-popup> -->
		<!-- <button type="primary" style="margin-top: 30rpx; width: 200rpx" @click="changeActive">改变状态</button> -->
		<!-- 	<uni-forms :modelValue="formData" label-position="left">
			<uni-forms-item :style="`margin-bottom: 10rpx;`" label="设备名称" name="name">
				<uni-easyinput type="text" v-model="formData.name" placeholder="请输入设备名称"></uni-easyinput>
			</uni-forms-item>

			<uni-forms-item label="密码" name="password">
				<uni-easyinput type="password" v-model="formData.password" placeholder="请输入设备名称"></uni-easyinput>
			</uni-forms-item>
			<button class="_button" @click="connect">connect {{count}}</button>
		</uni-forms>
		<uni-list>
			<uni-list-item clickable v-for="(item, index) in wifiList" :key="index" @click="onListClick(item,index)">
				<template v-slot:body>
					<view class="" style="flex:1;">
						<view>BSSID:{{item.BSSID}}</view>
						<view>SSID:{{item.SSID}}</view>
					</view>

				</template>
				<template v-slot:footer>
					<uni-icons type="locked" size="20"></uni-icons>
				</template>
			</uni-list-item>
		</uni-list> -->
		<uni-popup ref="alertDialog" type="dialog">
						<uni-popup-dialog :type="msgType" cancelText="关闭" confirmText="去链接" title="提示" content="配网成功,去链接家庭wifi" @confirm="dialogConfirm"
					@close="dialogClose"></uni-popup-dialog>
		</uni-popup>
	</view>
	
</template>

<script setup>
import { onMounted, ref, watch } from 'vue';

import { userConfigStore } from '@/stroe/useConfigStore.js';
import { storeToRefs } from 'pinia';
import { uniToast } from '@/utils';
import { onShow } from '@dcloudio/uni-app';
const userStroe = userConfigStore();
const { count } = storeToRefs(userStroe);

let inputDialog = ref();
let alertDialog = ref();
let formData = ref({
	SSID: '',
	password: ''
});
let adviceForm = ref({
	SSID: '',
	password: ''
});

let currentSystem= ref("");

let stepList = ref([
	{ title: '已开始', ativeTitle: '', processState: 0 },
	{ title: '已开始', ativeTitle: '', processState: 1 },
	{ title: '已开始', ativeTitle: '', processState: 2 },
	{ title: '已开始', ativeTitle: '', processState: 3 }
]);

let currentActive = ref(0);
let currentWifi = ref();
function changeActive() {
	if (currentActive.value < stepList.value.length - 1) {
		currentActive.value += 1;
	} else {
		currentActive.value = 0;
	}
}
//第一个下一步 android 获取wifi list ios 直接连接 设备wifi 
async function toSetp(index) {
	   currentActive.value = index;
	if(currentSystem.value == 'android'){
		try{
			uni.showLoading({
				title:"wifi列表加载中..."
			})
			let wfList = await getWifiList()
			wifiList.value = wfList?.wifiList || []; 
			uni.hideLoading()
		}catch(err){
			uniToast.toast("wifi列表获取失败")
		}
	}else if(currentSystem.value == 'ios'){
		// 获取wifi 列表同时 直接链接设备wifi
		let wfList = await getWifiList()
		wifiList.value = wfList?.wifiList || [];
	}
	
	

}
// 第二步 填写 家庭wifi 账号密码
async function toSetpCheck(index) {
	let wifi = await getConnectedWifi();
	console.log(wifi);
	if (wifi.errMsg == 'getConnectedWifi:ok') {
		uniToast.toast("当前链接wifi: ",wifi.wifi.SSID)
		currentWifi.value = wifi.wifi;
		// inputDialog.value.open();
		currentActive.value = index;
	} else {
		uniToast.toast('请连接设备wifi后重试');
	}
}

let wifiList = ref([]);
//点击 第一步的 wifi list 的 每一项
function onListClick(item, index) {
	if(currentSystem.value=='android'){
		// android 链接 item  (设备wifi)
		adviceForm.value = item;
		uni.connectWifi({
			SSID: adviceForm.value.SSID,
			password: adviceForm.value?.password || "",
			forceNewApi:true,
			maunal:true,
			success(res) {
				console.log("链接wifi",res)
				if(res.errMsg=="connectWifi:ok"){
					setTimeout(()=>{
						uni.getConnectedWifi({
							success(wifi){
								if(wifi.wifi.SSID == adviceForm.value.SSID){
									uniToast.toast("链接设备成功")
									currentActive.value = 2
								}else{
									uniToast.toast("请链接选中设备的wifi");
								}
							},
							fail(err){
								uniToast.toast("请连接选中设备wifi");
							}
						})
					},2000)
					
				}else{
					uniToast.toast("设备链接失败")
				}
			},
			fail(err) {
				uniToast.toast("设备链接失败")
				
			}
		});
		
	}else if(currentSystem.value = 'ios'){
		// ios 啥也不做
		
	}
	
	// inputDialog.value.open();
}
onShow(()=>{
	console.log("onSHow")
	
})
onMounted(async () => {
	// connect();
	// alertDialog.value.open()
	console.log("onMounted")
	 let currentProcess = await getSystem()
	 currentSystem.value = currentProcess
	 await startWifi(); 
	
	 console.log("当前系统",currentProcess)
	
});
function dialogConfirm(){
	uni.connectWifi({
		SSID: formData.value.SSID,
		password: formData.value.password,
		forceNewApi:true,
		maunal:true,
	})
}
//获取系统类型
function getSystem(){
	return new Promise((l,r)=>{
		let currentProcess = uni.getSystemInfoSync();
		l(currentProcess.platform);
	});
}
function touptemp(){
	 currentActive.value = currentActive.value - 1;
}

// wifi密码
async function dialogInputConfirm(val) {
	currentWifi.value['password'] = val;
	// currentActive.value = 2;
	try{
		let  curnetConnctWifi = await connectWifi({SSID:currentWifi.value.SSID,password:currentWifi.value.password})
	
	
	
	}catch(err){
		uniToast.toast("链接wifi 失败，请重新链接")
		currentWifi.value['password'] = "";
	}
	
	
}
function toAdviceContent(index){
	
	if(!formData.value.SSID){
		uniToast.toast("请输入家庭wifi SSID");
		return;
	}
	if(!formData.value.password){
		uniToast.toast("请输入家庭wifi 密码");
		return;
	}
	currentActive.value = index;
	// uni.showLoading({
	// 	title:'设备连接中'
	// })
	// uni.connectWifi({
	// 	SSID: adviceForm.value.SSID,
	// 	password: adviceForm.value.password,
	// 	forceNewApi:true,
	// 	maunal:true,
	// 	success(res) {
	// 		console.log("链接wifi",res)
	// 		if(res.errMsg=="connectWifi:ok"){
	// 			setTimeout(()=>{
	// 				uni.getConnectedWifi({
	// 					success(wifi){
	// 						if(wifi.wifi.SSID == adviceForm.value.SSID){
	// 							uniToast.toast("链接设备成功")
	// 							currentActive.value = 3
	// 						}else{
	// 							uniToast.toast("请链接选中设备的wifi");
	// 						}
	// 					},
	// 					fail(err){
	// 						uniToast.toast("请连接选中设备wifi");
	// 					}
	// 				})
	// 			},2000)
				
	// 		}else{
	// 			uniToast.toast("设备链接失败")
	// 		}
	// 	},
	// 	fail(err) {
	
	// 		uniToast.toast("设备链接失败")
			
	// 	}
	// });
}
function onListAdviceClick(item,index){
	formData.value.SSID = item.SSID;
}
function connectWifi({SSID,password}) {
	console.log(SSID,password)
	
	return new Promise((l, r) => {	
		uni.connectWifi({
			SSID: SSID,
			password: password,
			forceNewApi:true,
			maunal:true,
			success(res) {
				console.log("链接wifi",res)
				if(res.errMsg=="connectWifi:ok"){
					setTimeout(()=>{
						uni.getConnectedWifi({
							success(wifi){
								if(wifi.wifi.SSID == currentWifi.value.SSID){
									uniToast.toast("链接成功")
								}else{
									uniToast.toast("请链接选中的wifi");
								}
							},
							fail(err){
								uniToast.toast("请连接家庭wifi");
							}
						})
					},2000)
					l(true)
				}else{
					r(false)
				}
			},
			fail(err) {
		
				r(err);
				
			}
		});
		
	});
}
function sendMassage(data){
	uni.showLoading({
		title:"配网中...",
		mask:true,
	})
	
	try{
		uni.request({
			url:"http://192.168.4.1/submit",
			method:'POST',
			data:data,
			success(res){
				const {success , error} = res;
				if(success){
					// uniToast.toast("配网成功");
					currentActive.value = currentActive.value +1
					alertDialog.value.open()
				}else{
					if(error){
						uniToast.toast(error);
					}else{
						uniToast.toast("配网失败，请填写正确wifi和密码")
					}
				}
				
			}
		});
	}catch(err){
		uniToast.toast("配网失败，请填写正确wifi和密码")
	}finally{
		uni.hideLoading();
	}
	
}
async function toContent(){
 	// let res = await connectWifi({SSID:adviceForm.value.SSID,password:adviceForm.value.password})
	
// console.log("链接结果",res);
	// uniToast.toast(`发送的wifi ${formData.value.SSID},${formData.value.password}`)
  
   sendMassage({ssid:formData.value.SSID,password:formData.value.password})
}

// 获取wifiList
async function connect() {
	userStroe.increment();
	const wifi = await startWifi();
	const wfList = await getWifiList();
	wifiList.value = wfList?.wifiList || [];
}

// 获取wifi list
function getWifiList() {
	return new Promise((l, r) => {
		console.log("getListStart")
		uni.getWifiList({
			success: (res) => {
				console.log("wifi:list",res)
				if (res.errMsg == 'getWifiList:ok') {
					uni.onGetWifiList((listener) => {
						console.log(listener)
						// uniToast.toast('成功获取wifi列表');
						l(listener);
					});
				}
			},
			fail: (err) => {
				r(err);
			}
		});
	});
}

function getConnectedWifi() {
	return new Promise((l, r) => {
		uni.getConnectedWifi({
			// partialInfo:true,
			success(res) {
				l(res);
			},
			fail(err) {
				console.log(err);
				r(err);
			}
		});
	});
}
//初始化wifi模块
function startWifi() {
	return new Promise((l, r) => {
		uni.startWifi({
			success: (res) => {
				console.log(res);
				if (res.errMsg == 'startWifi:ok') {
					// uniToast.toast('wifi模块初始化');
					l(res);
				}
			},
			fail: (err) => {
				uniToast.toast('wifi模块初始化失败');
				r(err);
			}
		});
	});
}
</script>

<style lang="scss">
.teps {
	display: flex;
	align-items: center;

	.item_teps {
		flex: 1;
		text-align: center;
		.active_item_imm {
			// background:#f25;
			width: 100%;
			.procefindding {
				.line {
					display: flex;
					align-items: center;
					width: 100%;
					.active_icons_num {
						width: 24px;
						height: 24px;
						border-radius: 50%;
						line-height: 24px;
						border: solid 1rpx #9ef2a9;
						text-align: center;
						font-size: 24rpx;
						color: #fff;
						background: #9ef2a9;
					}
					.icons_num {
						width: 24px;
						height: 24px;
						border-radius: 50%;
						line-height: 24px;
						border: solid 1rpx #bbbbbb;
						text-align: center;
						font-size: 24rpx;
						color: #bbbbbb;
					}

					.left {
						flex: 1;
						height: 4rpx;
						background: #9ef2a9;
					}
					.right {
						flex: 1;
						height: 4rpx;
						background: #9ef2a9;
					}

					.rightclolr {
						background: #bbbbbb;
					}
					.hidder_line {
						background: transparent;
					}
				}
				.text {
					margin: 10rpx;
					font-size: 28rpx;
					color: #9ef2a9;
				}
				.clolrb {
					color: #bbbbbb;
				}
			}
		}
	}
}

.content_container {
	min-height: 900rpx;
	background: #fff;
	border-radius: 20rpx;
	padding: 40rpx;
	display: flex;
	flex-direction: column;
	margin-top:40rpx;
	.content_container_botton {
		margin-top: auto;
		width:300rpx;
		background: blue;
		color:#fff;
	}
}
.wifi_list{
	height:700rpx;
	// background:#f25;
}
.wifi_list_two{
	height:500rpx;
	
}

._button {
	color: #333;
	background: #fff;
	border-radius: 20rpx;
	border: solid 1rpx #3333;
	margin-bottom: 50rpx;
	height: 80rpx;
	padding: 0;
	margin: 50rpx 0;
	line-height: 80rpx;
	font-size: 30rpx;
}

.uni-forms-item {
	margin-bottom: 30rpx !important;
}

._button::after {
	border: none;
	margin: 0;
	padding: 0;
	background-color: transparent;
}

.content {
	margin-top: 100rpx;
	padding: 0 30rpx;
}

.logo {
	height: 200rpx;
	width: 200rpx;
	margin-top: 200rpx;
	margin-left: auto;
	margin-right: auto;
	margin-bottom: 50rpx;
}

.text-area {
	display: flex;
	justify-content: center;
}

.title {
	font-size: 36rpx;
	color: #8f8f94;
}
</style>
